package dao;


import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import entity.Peason;

public class BaseDAO<T,ID> {
	private EntityManager entityManager=EntityManagerUtils.getEntityManager();
	private Class<T> clazz=GenericsUtils.getSuperClassGenricType(getClass());
	private String EntityClassName=clazz.getName();
	
	public EntityManager getEntityManager() {
		return entityManager;
	}

	public T findById(ID id) {
		T model = entityManager.find(clazz, id);
		return model;
	}
	
	public List<Peason> findAll(){
		String hql="from "+EntityClassName;
		Query query = entityManager.createQuery(hql);
		return query.getResultList();
	}
	
	public void save(T model) {
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		entityManager.persist(model);
		transaction.commit();
	}
	
	public void deleteById(ID id) {
		T model = findById(id);
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		entityManager.remove(model);
		transaction.commit();
	}
	
	public void delete(T model) {
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		entityManager.remove(model);
		transaction.commit();
	}
	
	public List<T> findByPropity(String propityName,Object propity) {
		String hql="from "+EntityClassName+" where "+propityName+"= ?1";
		Query query = entityManager.createQuery(hql);
		query.setParameter(1, propity);
		return query.getResultList();
	}
	
	public List<T> findByPropityLike(String propityName,String value){
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<T> createQuery = criteriaBuilder.createQuery(clazz);
		Root<T> tRoot = createQuery.from(clazz);
		Predicate condition = criteriaBuilder.like(tRoot.get(propityName).as(String.class), "%"+value+"%");
		createQuery.where(condition);
		TypedQuery<T> query = entityManager.createQuery(createQuery);
		return query.getResultList();
		
	}
	
	
}


